package com.example.demo.thread.race;


import java.util.Random;

/**
 * @author: htc
 * @date: Created in 14:11 2019/1/7.
 */
public class RaceConditionDemo {
    public static void main(String[] args) {
        //客户端线程数
        int numberOfThreads = args.length > 0 ? Short.valueOf(args[0]) : Runtime.getRuntime().availableProcessors();
        Thread[] workerThreads = new Thread[numberOfThreads];
        for (int i = 0; i < numberOfThreads; i++) {
            workerThreads[i] = new WorkerThread(i, 10);
        }

        //待所有线程创建完毕后，再一次性将其启动，以便这些线程都能够尽可能地在同一时间内运行
        for (Thread t : workerThreads) {
            t.start();
        }
    }

    static class WorkerThread extends Thread {
        private final int requestCount;

        public WorkerThread(int id, int requestCount) {
            super("worker-" + id);
            this.requestCount = requestCount;
        }

        @Override
        public void run() {
            int i = requestCount;
            String requestID;
            RequestIDGenerator requestIDGenerator = RequestIDGenerator.getInstance();
            while (i-- >0){
                //生成request ID
                requestID = requestIDGenerator.nextID();
                processRequest(requestID);
            }
        }

        /**
         * 模拟请求处理
         * @param requestID
         */
        private void processRequest(String requestID) {
            //模拟请求处理耗时
            try {
                Thread.sleep(new Random().nextInt(50));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.printf("%s got requestId: %s %n",Thread.currentThread().getName(), requestID);
        }
    }
}
